// src/main/java/org/zachary/creditbusiness/hotel/sched/BanScheduler.java
package org.zachary.creditbusiness.hotel.scheduler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.stereotype.Component;
import org.zachary.creditbusiness.hotel.entity.Ban;
import org.zachary.creditbusiness.hotel.entity.Reservation;
import org.zachary.creditbusiness.hotel.mapper.BanMapper;
import org.zachary.creditbusiness.hotel.mapper.ReservationMapper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
@Slf4j
public class BanScheduler {

    private final ReservationMapper reservationMapper;
    private final BanMapper         banMapper;

    private static final DateTimeFormatter DTF =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public BanScheduler(ReservationMapper reservationMapper, BanMapper banMapper) {
        this.reservationMapper = reservationMapper;
        this.banMapper         = banMapper;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        log.info("ApplicationReadyEvent — extreme-overdue ban check");
        checkAndBan();
    }

    private void checkAndBan() {
        LocalDate today = LocalDate.now();
        log.info("Checking extreme overdue at {}", today);

        // 查所有已逾期(promise=2)且未支付(is_pay=0)
        QueryWrapper<Reservation> qw = new QueryWrapper<>();
        qw.eq("promise", 2)
                .eq("is_pay", 0);
        List<Reservation> list = reservationMapper.selectList(qw);
        log.info("Found {} overdue unpaid reservations", list.size());

        for (Reservation r : list) {
            try {
                LocalDate checkout =
                        LocalDateTime.parse(r.getCheckoutDate(), DTF).toLocalDate();
                long days = ChronoUnit.DAYS.between(checkout, today);
                if (days <= 180) {
                    continue;
                }
                String banUuid = r.getUuid();
                if (banUuid == null) {
                    log.warn("Reservation {} has no uuid, skip ban", r.getOrderId());
                    continue;
                }
                // 只插入不存在的 uuid
                if (banMapper.selectById(banUuid) == null) {
                    Ban ban = new Ban();
                    ban.setUuid(banUuid);
                    ban.setUserId(r.getUserId().longValue());
                    ban.setBan(1);
                    banMapper.insert(ban);
                    log.info("Banned (extreme) reservation {} -> user {} ({} days)",
                            r.getOrderId(), r.getUserId(), days);
                }
            } catch (Exception ex) {
                log.error("Error processing order {} checkoutDate={}",
                        r.getOrderId(), r.getCheckoutDate(), ex);
            }
        }
    }
}